package com.kingdee.jdy.controller;

import com.alibaba.fastjson.JSONObject;
import com.kingdee.jdy.util.AccessTokenUtil;
import com.kingdee.jdy.util.HttpUtil;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {

    @Value("${demo.client_id}")
    public static String client_id;

    @Value("${demo.client_secret}")
    public static String client_secret;

    @Value("${demo.username}")
    public static String username;

    @Value("${demo.password}")
    public static String password;

    @ResponseBody
    @RequestMapping(path = "/helloworld")
    public String getAccessToken(@RequestParam(name = "code") String code){

        String resMsg = "";
        JSONObject res = AccessTokenUtil.GetAccessTokenByAuth2(code);
        if (res != null) {
            String errcode = res.getString("errcode");
            if (errcode.equalsIgnoreCase("0")) {
                String token = res.getJSONObject("data").getString("access_token");
                resMsg = "auth2 获取token成功 token:" + token;
            } else {
                resMsg = "auth2 获取token失败！" + res.getString("description");
            }
        }

        System.out.println(resMsg);
        return resMsg;
    }


    @ResponseBody
    @RequestMapping(path = "/sso")
    public String SSO(){

        JSONObject res = new JSONObject();
        String ssoUrl = "";
        try {
            String auth_code = "";
            String accessToken = AccessTokenUtil.GetAccessToken();
            JSONObject jsonObject = AccessTokenUtil.GetAuth_code(accessToken);
            if (jsonObject != null) {
                int errcode = jsonObject.getIntValue("errcode");
                if (errcode == 0) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (data != null) {
                        auth_code = data.getString("auth_code");
                        ssoUrl = "https://api.kingdee.com/auth/user/onelogin?auth_code=" + auth_code + "&redirect_uri=https://one.kingdee.com/?category_code=C06";
                    }
                }
            }
            res.put("err", 0);
            res.put("ssoUrl", ssoUrl);
        } catch (Exception e) {
            res.put("err", 1);
        }

        return res.toJSONString();
    }

}
